package com.tnl.app.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

//import com.jeeplus.common.config.Global;
//import com.jeeplus.common.utils.DateUtils;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.wxaapp.api.WxaTemplate;
import com.tnl.app.dao.CityDAO;
import com.tnl.app.dao.DomainDAO;
import com.tnl.app.dao.EvaluateDAO;
import com.tnl.app.dao.HunterDAO;
import com.tnl.app.dao.MyCalendarDAO;
import com.tnl.app.dao.OrderDAO;
import com.tnl.app.dao.OrderDescDAO;
import com.tnl.app.dao.SafedsalesDAO;
import com.tnl.app.entity.City;
import com.tnl.app.entity.Domain;
import com.tnl.app.entity.Employee;
import com.tnl.app.entity.Hunter;
import com.tnl.app.entity.Order;
import com.tnl.app.entity.OrderDesc;
import com.tnl.app.entity.PayInfo;
import com.tnl.app.entity.Person;
import com.tnl.app.entity.Safedsales;
import com.tnl.app.entity.TemplateData;
import com.tnl.app.service.IEmployeeService;
import com.tnl.app.service.UserService;
import com.tnl.app.service.impl.SMSService;
import com.tnl.app.vo.PayParam;
import com.tnl.base.Const;
import com.tnl.base.SystemConfig;
import com.tnl.base.web.JsonController;
import com.tnl.utils.ClientCustomSSL;
import com.tnl.utils.DateUtil;
import com.tnl.utils.PayCommUtil;
import com.tnl.utils.RadomUtils;
import com.tnl.utils.SMSUtils;
import com.tnl.utils.UrlUtil;
import com.tnl.utils.WxaTemplateUtil;

@Controller
@RequestMapping("/pay")
public class PayController extends JsonController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private OrderDAO orderDAO;
    @Autowired
    private OrderDescDAO orderDescDAO;
    @Autowired
    private HunterDAO hunterDAO;
    @Autowired
    private DomainDAO domainDAO;
    @Autowired
    private CityDAO cityDAO;
    @Autowired
    private EvaluateDAO evaluateDAO;
    @Autowired
    private SafedsalesDAO safedsalesDAO;

    @Autowired
    private MyCalendarDAO myCalendarDAO;
    @Autowired
    private SMSService smsService;

    private String appid = SystemConfig.getProperties("appid");
    private String app_key = SystemConfig.getProperties("app_key");

    private static Logger log = Logger.getLogger(PayController.class);

    @RequestMapping(value = "/prepay")
    public void prePay(HttpServletResponse response, HttpServletRequest request, String code, String openid,
                       Double totalfee, Integer orderId, Integer ordescId) {

        boolean result = true;
        String info = "";
        String prepayId = "";
        String nonceStr = "";
        String randomOrderId = "";

        if (StringUtils.isBlank(openid)) {
            result = false;
            info = "获取到openId为空";
        } else {
            openid = openid.replace("\"", "").trim();
            String clientIP = PayCommUtil.getClientIp(request);
            if (StringUtils.isBlank(clientIP)) {
                clientIP = "8.8.8.8";
            }
            nonceStr = RadomUtils.generateMixString(32);
            totalfee = totalfee * 100;
            randomOrderId = DateUtil.currentTimeStr() + RadomUtils.autoAddPlus();
            prepayId = unifiedOrder(openid, clientIP, totalfee, nonceStr, randomOrderId, ordescId);

            if (StringUtils.isBlank(prepayId)) {
                result = false;
                info = "出错了，未获取到prepayId";
            }
        }
        if (result) {
            this.successJson(new PayParam(prepayId, nonceStr, app_key, appid, randomOrderId), "成功调起支付窗口", response);
        } else {
            this.errorJson(null, info, response);
        }
    }

    @RequestMapping(value = "/prepaydiff")
    public void prePayDiff(HttpServletResponse response, HttpServletRequest request, String code, String openid,
                           Double totalfee, Integer orderId) {

        boolean result = true;
        String info = "";
        String prepayId = "";
        String nonceStr = "";
        String randomOrderId = "";
        if (StringUtils.isBlank(openid)) {
            result = false;
            info = "获取到openId为空";
        } else {
            openid = openid.replace("\"", "").trim();
            String clientIP = PayCommUtil.getClientIp(request);
            if (StringUtils.isBlank(clientIP)) {
                clientIP = "8.8.8.8";
            }
            nonceStr = RadomUtils.generateMixString(32);
            totalfee = totalfee * 100;
            randomOrderId = orderId + "-" + DateUtil.currentTimeStr() + RadomUtils.autoAddPlus();
            Order order = orderDAO.getById(orderId);
            Integer ordescId = order.getOrdescId();
            prepayId = unifiedOrder(openid, clientIP, totalfee, nonceStr, randomOrderId, ordescId);

            if (StringUtils.isBlank(prepayId)) {
                result = false;
                info = "出错了，未获取到prepayId";
            }
        }
        if (result) {
            this.successJson(new PayParam(prepayId, nonceStr, app_key, appid, randomOrderId), "成功调起支付窗口", response);
        } else {
            this.errorJson(null, info, response);
        }
    }

    /**
     * @return
     * @throws Exception
     * @Description:微信支付
     */
    @RequestMapping(value = "/wxNotify")
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        // 为微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";
        System.out.println("接收到的报文：" + notityXml);
        // XML外部实体注入漏洞（XXE）-update by adela 2019/04/25
        Map map = PayCommUtil.parseXml(notityXml);
//        Map map = PayCommUtil.xmlToMap(notityXml);  鏂规硶鏈夐棶棰橈紝绋嬪簭璧板埌杩欓噷璧颁笉涓嬪幓浜�

        String openId = (String) map.get("openid");
        String returnCode = (String) map.get("return_code");

        String out_trade_no = (String) map.get("out_trade_no");
        String transaction_id = (String) map.get("transaction_id");
        String attach = (String) map.get("attach");

        String total_fee = (String) map.get("total_fee");
        String time_end = (String) map.get("time_end");

        if (PaymentKit.verifyNotify(map, Const.APP_KEY)) {
            if ("SUCCESS".equals(returnCode)) {

                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                formatter.setLenient(false);
                Date newDate = formatter.parse(time_end);
                formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String pay_time = formatter.format(newDate);
                if (out_trade_no.indexOf("-") != -1) {
                    String orderId = out_trade_no.substring(0, out_trade_no.indexOf("-"));
                    int res = orderDAO.updateDiffStatus(transaction_id, Integer.parseInt(orderId));
                } else {
                    Order order = new Order();
                    order.setOpenid(openId);
                    ;
                    order.setOrdercode(out_trade_no);
                    order.setOrdescId(Integer.parseInt(attach));
                    order.setTransactionId(transaction_id);
                    order.setPayMoney(Integer.parseInt(total_fee));
                    int res = orderDAO.updateTransactionId(order);
                }
            }
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            this.errorJson(resXml, "fail", response);
        }
        System.out.println(resXml);
        System.out.println("微信支付回调数据结束");

        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
        this.successJson(resXml, "success", response);
    }

    /**
     * @param merchantNumber      商户这边的订单号
     * @param wxTransactionNumber 微信那边的交易单号
     * @param totalFee            订单的金额
     * @Author: KIKI 退款目前只支持整数金额，因为数据库订单金额，已经定调为int了。
     * @Description:微信退款 注意：：微信金额的单位是分 所以这里要X100 转成int是因为 退款的时候不能有小数点
     * @Date: 2018-3-12 11:18 order.getOrdercode(), order.getTransactionId(),
     * order.getPayMoney()
     */
    @RequestMapping(value = "refundone")
    public Object wxPayRefundone(String merchantNumber, String wxTransactionNumber, int totalFee) {
        Object object = ClientCustomSSL.setUrl(merchantNumber, wxTransactionNumber, totalFee);
        return object;
    }

    /**
     * 支付成功新增订单 openid
     */
    @RequestMapping(value = "addOrder")
    public void addOrder(HttpServletResponse response, String openid, String unionid, String ordercode,
                         Integer hunterId, Integer ordescId, Integer orderMoney, String orderTime, String proType, String formId,
                         String orderformId) {
        int flag = 0;

        Employee emp = employeeService.getEmpByUnionid(unionid);
        System.out.println("STEP3:emp=" + emp.getId() + emp.getEmpid());
        Order order = orderDAO.getOrderByCode(ordercode);
        Hunter hunter = hunterDAO.getById(hunterId);

        if (emp != null) {
            flag = orderDAO.updateHunterInfo(emp.getEmpid(), hunterId, orderMoney, 0, orderTime, proType, ordercode);
            // isbook:1已预定，0是未预定
            myCalendarDAO.updateIsBooking(hunterId, orderTime, 1);
            OrderDesc orderdesc = orderDescDAO.getById(order.getOrdescId());
            // send sms
            try {
                if (orderdesc.getTag().equals(Const.ResumeTag) || orderdesc.getTag().equals(Const.InterviewTag)) {
                    smsService.sendHunterOrderSMS2(hunter.getPhone(), orderTime.substring(5, 7),
                            orderTime.substring(8, 10),
                            "https://www.tiaonali.com/tnl-hunter/wechat/hunter/toOrderDetail.do?orderId="
                                    + order.getId());
                } else {
                    smsService.sendHunterOrderSMS(hunter.getPhone(), orderTime.substring(5, 7),
                            orderTime.substring(8, 10), orderdesc.getName(),
                            "https://www.tiaonali.com/tnl-hunter/wechat/hunter/toOrderDetail.do?orderId="
                                    + order.getId());
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                log.error(e.getMessage());
            }

            // 推送给候选人
            try {


                try {
                    String content = "您已成功预约" + orderdesc.getName() + "咨询服务！请耐心等待顾问处理订单。为了顾问能提前了解您的情况，您需完善咨询信息，前往小程序（个人中心-我的咨询-订单待接单详情页完善）。如有问题，可咨询18721386781。";
                    SMSUtils.sendSmsOrderToUser(emp.getPhone(), content);
                } catch (Exception e) {
                    log.error(e.getMessage());
                }


                // push hunter
                String tempjsonhunter = TemplateData.New().setTouser(hunter.getOpenid())
                        .setTemplate_id("6uworxVd1x4wnjjobW6OoW2k25bZ9NCw9yvI71OAJZg")
                        .setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/toOrderDetail.do?orderId="
                                + order.getId())
                        .add("first", hunter.getName() + "顾问您好，有用户向您发起了" + orderdesc.getName() + "咨询预约，请尽快接单。", "#274084").add("keyword1", "YQS" + ordercode, "#000000")
                        .add("keyword2", orderMoney + "元「￥" + orderdesc.getSpec() + "/" + orderdesc.getName() + "」",
                                "#F47e2d")
                        .add("keyword3", order.getCreateTime(), "#000000").add("remark", "点击查看订单详情并接单", "#274084")
                        .build();
                System.out.println(tempjsonhunter);
                ApiResult reshunter = TemplateMsgApi.send(tempjsonhunter);
                System.out.println("模板消息发送结果：" + reshunter);
                // push msg
                try {
                    System.out.println("短信通知顾问 " + hunter.getPhone() + "，有客户下单！");
                    String content = hunter.getName() + "顾问您好，有用户向您发起了" + orderdesc.getName() + "咨询预约，请至微信公众号[headoffer会猎]菜单栏[顾问]-[预约管理]";
                    SMSUtils.sendSmsOrderToHunter(hunter.getPhone(), hunter.getName(), content);
                } catch (Exception e) {
                    log.error(e.getMessage());
                }

            }catch (Exception exception){
            	log.error("error :"+ exception.getMessage());
			}
            System.out.println("END. RESULT=" + flag);

            if (flag > 1) {
                this.successJson(flag, "order add success", response);
            } else {
                this.errorJson(flag, "order add fail", response);
            }
        }
    }

    @RequestMapping(value = "updOrder")
    public void updOrder(HttpServletResponse response, String openid, String unionid, String orderId, String
            orderMoney,
                         String formId) {
        int flag = 0;
        Employee emp = employeeService.getEmpByUnionid(unionid);
        System.out.println("STEP3:emp=" + emp.getId() + emp.getEmpid());
        Order order = orderDAO.getById(Integer.parseInt(orderId));
        Hunter hunter = null;
        if (order != null) {
            hunter = hunterDAO.getById(order.getHunterId());
        }
        if (emp != null) {// 蹇呴』濉啓涓汉璧勬枡
            // isbook:1宸查瀹氾紝0鏄湭棰勫畾
            OrderDesc orderdesc = orderDescDAO.getById(order.getOrdescId());
            // push candidate or wxapp 鍘焗WsepIDqjQy9ZJ258XYgnvaGzlEEeLx6tiEvtnc2f0I
//		      	String tempjson=new WxaTemplate()
//		      			.setTemplate_id("9x1nfHb4ZMvQb0HkggeIgTVnVolYtw1Vzx6ywpy1NsU")
//		      			.setForm_id(formId)
//		      			.setTouser(openid)
//		      			.setPage("pages/my-ordetail/my-ordetail?orderId="+order.getId())
//		      			.add("keyword1", "YQS"+order.getOrdercode(), "#000000")
//						.add("keyword2", order.getCreateTime(), "#000000")
//						.add("keyword3", "銆岋骏"+orderdesc.getSpec()+"/"+orderdesc.getName()+"銆�", "#000000")
//						.add("keyword4", orderMoney+"鍏�", "#F47e2d")
//						.add("keyword5", "宸叉敮浠�","#000000")
//						.add("keyword6", "鎰熻阿淇′换骞惰ˉ瓒充綑娆�,闈炲父鎰熻阿锛�", "#00000")
//						.build();
//				System.out.println(tempjson);
//				boolean res=WxaTemplateUtil.sendTemplateMsg(tempjson);
//				System.out.println("妯℃澘娑堟伅鍙戦�佺粨鏋滐細"+res);

            // push hunter
            String tempjsonhunter = TemplateData.New().setTouser(hunter.getOpenid())
                    .setTemplate_id("6uworxVd1x4wnjjobW6OoW2k25bZ9NCw9yvI71OAJZg")
                    .setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/toOrderDetail.do?orderId="
                            + order.getId())
                    .add("first", "您好，客户已支付订单，请您按时咨询服务", "#274084")
                    .add("keyword1", "YQS" + order.getOrdercode(), "#000000")
                    .add("keyword2", orderMoney + "元「￥" + orderdesc.getSpec() + "/" + orderdesc.getName() + "」",
                            "#F47e2d")
                    .add("keyword3", order.getCreateTime(), "#000000").add("remark", "温馨提示：请您点击详情进行订单确认。", "#274084")
                    .build();
            System.out.println(tempjsonhunter);
            ApiResult reshunter = TemplateMsgApi.send(tempjsonhunter);
            System.out.println("模板消息发送结果：" + reshunter);
        }
        System.out.println("END. RESULT=" + flag);

        if (flag > 1) {
            this.successJson(flag, "order add success", response);
        } else {
            this.errorJson(flag, "order add fail", response);
        }

    }

    public void pushMsg(String url, String orderformId, String openid, String ordercode, Integer orderMoney,
                        OrderDesc orderdesc, Order order, String pushStr) {
        String ordertempjson = new WxaTemplate().setTemplate_id("eP6aJTmjVJUiEaU9q3lHOdvsjmnnqnG8WuwRUucbxUU")
                .setForm_id(orderformId).setTouser(openid)
                .setPage("pages/my-ordetail-resume/web-view?orderId=" + order.getId() + "&url=" + url)
                .add("keyword1", "YQS" + ordercode, "#000000").add("keyword2", "进行中", "#000000")
                .add("keyword3", orderMoney + "元", "#F47e2d")
                .add("keyword4", "「￥" + orderdesc.getSpec() + "/" + orderdesc.getName() + "」", "#000000")
                .add("keyword5", "您好，您预约的「￥" + orderdesc.getSpec() + "/" + orderdesc.getName() + "」," + pushStr + "。",
                        "#00000")
                .build();
        System.out.println(ordertempjson);
        boolean orderRes = WxaTemplateUtil.sendTemplateMsg(ordertempjson);
        System.out.println(orderdesc.getTag() + "模板消息发送结果：" + orderRes);
    }

    /**
     * 我的预定（status=-1退款,0待接单，1进行中，2维权中，3已完成，4已取消，5已拒单,6已评价）
     *
     * @param response
     * @param openid
     */

    @RequestMapping(value = "getUnOrderByStatus")
    public void getUnOrderByStatus(HttpServletResponse response, String openid, Integer status) {
        // 待接单
        List<Order> unorder = orderDAO.getOrdersByStatus(openid, status);
        for (Order order : unorder) {
            int itemid = order.getOrdescId();
            OrderDesc orderDesc = orderDescDAO.getById(itemid);
            if (orderDesc != null) {
                order.setOrderdesc(orderDesc.getName());
                order.setOrdercode("YQS" + order.getOrdercode());
            }
            int hunterid = order.getHunterId();
            Hunter hunter = hunterDAO.getById(hunterid);
            if (hunter != null) {
                order.setHuntername(hunter.getName());
                order.setHeadImgUrl(
                        hunter.getImageUrl() != null ? Const.IMAGE_PATH + hunter.getImageUrl() : Const.IMAGE);
                order.setCityName(hunter.getCityName());
                order.setWorkage(hunter.getWorkage());
                order.setDomainName1(hunter.getDomainName1());
                order.setDomainName2(hunter.getDomainName2());
                order.setDomainName3(hunter.getDomainName3());
                order.setStatusName("待接单");
            }

        }
        this.successJson(unorder, "待接单", response);
    }

    @RequestMapping(value = "getOrderingByStatus")
    public void getOrderingByStatus(HttpServletResponse response, String openid, Integer status) {
        // openid="oLl4E5mILVE3pEf3QS7YoMZHTHQY";
        // 进行中
        List<Order> ordering = orderDAO.getOrdersByStatus(openid, status);
        for (Order order : ordering) {
            int itemid = order.getOrdescId();
            OrderDesc orderDesc = orderDescDAO.getById(itemid);
            if (orderDesc != null) {
                order.setOrderdesc(orderDesc.getName());
                order.setOrdercode("YQS" + order.getOrdercode());
            }
            int hunterid = order.getHunterId();
            Hunter hunter = hunterDAO.getById(hunterid);
            if (hunter != null) {
                order.setHuntername(hunter.getName());
                order.setHeadImgUrl(
                        hunter.getImageUrl() != null ? Const.IMAGE_PATH + hunter.getImageUrl() : Const.IMAGE);
                order.setCityName(hunter.getCityName());
                order.setWorkage(hunter.getWorkage());
                order.setDomainName1(hunter.getDomainName1());
                order.setDomainName2(hunter.getDomainName2());
                order.setDomainName3(hunter.getDomainName3());
                order.setStatusName("进行中");
                order.setPhone(hunter.getPhone());
                order.setEnglishname(hunter.getEnglishname());
            }

        }
        this.successJson(ordering, "进行中", response);
    }

    @RequestMapping(value = "getSafeOrderByStatus")
    public void getSafeOrderByStatus(HttpServletResponse response, String openid, Integer status) {
        // 维权中
        List<Order> safeorder = orderDAO.getOrdersByStatus(openid, status);
        for (Order order : safeorder) {
            int itemid = order.getOrdescId();
            OrderDesc orderDesc = orderDescDAO.getById(itemid);
            if (orderDesc != null) {
                order.setOrderdesc(orderDesc.getName());
                order.setOrdercode("YQS" + order.getOrdercode());
            }
            int hunterid = order.getHunterId();
            Hunter hunter = hunterDAO.getById(hunterid);
            if (hunter != null) {
                order.setHuntername(hunter.getName());
                order.setHeadImgUrl(
                        hunter.getImageUrl() != null ? Const.IMAGE_PATH + hunter.getImageUrl() : Const.IMAGE);
                order.setCityName(hunter.getCityName());
                order.setWorkage(hunter.getWorkage());
                order.setDomainName1(hunter.getDomainName1());
                order.setDomainName2(hunter.getDomainName2());
                order.setDomainName3(hunter.getDomainName3());
                order.setStatusName("维权中");
                order.setPhone(hunter.getPhone());
                order.setEnglishname(hunter.getEnglishname());
            }
        }
        this.successJson(safeorder, "维权中", response);
    }

    @RequestMapping(value = "getAssessOrderByStatus")
    public void getAssessOrderByStatus(HttpServletResponse response, String openid, Integer status) {
        // 待评价状态3
        List<Order> safeorder = orderDAO.getOrdersByStatus(openid, status);
        for (Order order : safeorder) {
            int itemid = order.getOrdescId();
            OrderDesc orderDesc = orderDescDAO.getById(itemid);
            if (orderDesc != null) {
                order.setOrderdesc(orderDesc.getName());
                order.setOrdercode("YQS" + order.getOrdercode());
            }
            int hunterid = order.getHunterId();
            Hunter hunter = hunterDAO.getById(hunterid);
            if (hunter != null) {
                order.setHuntername(hunter.getName());
                order.setHeadImgUrl(
                        hunter.getImageUrl() != null ? Const.IMAGE_PATH + hunter.getImageUrl() : Const.IMAGE);
                order.setCityName(hunter.getCityName());
                order.setWorkage(hunter.getWorkage());
                order.setDomainName1(hunter.getDomainName1());
                order.setDomainName2(hunter.getDomainName2());
                order.setDomainName3(hunter.getDomainName3());
                order.setStatusName("待评价");
                order.setPhone(hunter.getPhone());
                order.setEnglishname(hunter.getEnglishname());
            }
        }
        this.successJson(safeorder, "待评价", response);
    }

    @RequestMapping(value = "getOrderedByStatus")
    public void getOrderedByStatus(HttpServletResponse response, String openid, Integer status) {
        // 已完成
        List<Order> ordered = orderDAO.getOrdersByCompStatus(openid, status);
        for (Order order : ordered) {
            int itemid = order.getOrdescId();
            OrderDesc orderDesc = orderDescDAO.getById(itemid);
            if (orderDesc != null) {
                order.setOrderdesc(orderDesc.getName());
                order.setOrdercode("YQS" + order.getOrdercode());
            }
            int hunterid = order.getHunterId();
            Hunter hunter = hunterDAO.getById(hunterid);
            if (hunter != null) {
                order.setHuntername(hunter.getName());
                order.setHeadImgUrl(
                        hunter.getImageUrl() != null ? Const.IMAGE_PATH + hunter.getImageUrl() : Const.IMAGE);
                order.setCityName(hunter.getCityName());
                order.setWorkage(hunter.getWorkage());
                order.setDomainName1(hunter.getDomainName1());
                order.setDomainName2(hunter.getDomainName2());
                order.setDomainName3(hunter.getDomainName3());
                order.setPhone(hunter.getPhone());
                order.setEnglishname(hunter.getEnglishname());
            }
            if (order.getStatus() == 4) {
                order.setStatusName("已取消");
            } else if (order.getStatus() == 5) {
                order.setStatusName("已拒单");
            } else if (order.getStatus() == 6) {
                order.setStatusName("已评价");
            }
        }
        this.successJson(ordered, "已完成", response);
    }

    @RequestMapping(value = "getOrderedById")
    public void getOrderedById(HttpServletResponse response, Integer orderId) {
        // 已完成
        Order order = orderDAO.getById(orderId);
        int itemid = order.getOrdescId();
        OrderDesc orderDesc = orderDescDAO.getById(itemid);
        if (orderDesc != null) {
            order.setOrderdesc(orderDesc.getName());
            order.setOrdercode("YQS" + order.getOrdercode());
        }
        order.setTag(orderDesc.getTag());
        int hunterid = order.getHunterId();
        Hunter hunter = hunterDAO.getById(hunterid);
        if (hunter != null) {
            order.setHuntername(hunter.getName());
            order.setHeadImgUrl(hunter.getImageUrl() != null ? Const.IMAGE_PATH + hunter.getImageUrl() : Const.IMAGE);
            order.setCityName(hunter.getCityName());
            order.setWorkage(hunter.getWorkage());
            order.setDomainName1(hunter.getDomainName1());
            order.setDomainName2(hunter.getDomainName2());
            order.setDomainName3(hunter.getDomainName3());
            if (order.getStatus() == 0) {
                order.setStatusName("待接单");
            } else if (order.getStatus() == 1) {
                order.setStatusName("进行中");
            } else if (order.getStatus() == 2) {
                order.setStatusName("维权中");
            } else if (order.getStatus() == 3) {
                order.setStatusName("已完成");
            } else if (order.getStatus() == 4) {
                order.setStatusName("已取消");
            } else if (order.getStatus() == 5) {
                order.setStatusName("已拒单");
            } else if (order.getStatus() == 6) {
                order.setStatusName("已评价");
            } else if (order.getStatus() == 7) {
                order.setStatusName("顾问已确认完成，待您确认");
            }
        }

        this.successJson(order, "我的订单", response);
    }

    @RequestMapping(value = "updatePaystatus")
    public void updatePaystatus(HttpServletResponse response, Integer status, Integer payStatus, Integer orderid,
                                String formid) {
        int flag = orderDAO.updatePaystatus(payStatus, orderid);
        Order order = orderDAO.getById(orderid);
        Employee emp = employeeService.getByEmpId(order.getEmployeeId());
        Hunter hunter = hunterDAO.getById(order.getHunterId());
        OrderDesc orderdesc = orderDescDAO.getById(order.getOrdescId());
        if (status == 5 && emp != null && hunter != null) {
            wxPayRefundone(order.getOrdercode(), order.getTransactionId(), order.getPayMoney());
            // isbook:1已预定，0是未预定
            myCalendarDAO.updateIsBooking(order.getHunterId(), order.getOrderTime(), 0);
            // push candidate
//	        String tempjson =  new WxaTemplate()
//					.setTouser(emp.getOpenid())
//					.setTemplate_id("KrS5G3h6UxjTizgVwclpOIjzU_LnGslVcvqrHj7yuGI")
//					.setForm_id(formid)
//					.setPage("pages/my-ordetail/my-ordetail?orderId="+order.getId())
//					.add("keyword1", "YQS"+order.getOrdercode(), "#274084")
//					.add("keyword2", "锟�"+orderdesc.getSpec()+"/"+orderdesc.getName(), "#000000")
//					.add("keyword3", String.valueOf(order.getPayMoney()*0.01)+"鍏�", "#F47e2d")
//					.add("keyword4", order.getTransactionId(),"#000000")
//					.add("keyword5", DateUtil.currentTime(),"#000000")
//					.add("keyword6", "宸查��娆�","#000000")
//					.add("keyword7", "鎮ㄥソ锛屾偍鐨勮鍗曞凡鎴愬姛閫�娆撅紝鎴戜滑浼氬湪1-5涓伐浣滄棩鍐呭皢閽辨鎵撳叆鎮ㄧ殑浠樻璐︽埛锛岃娉ㄦ剰鏍稿锛佸鏈夌枒闂�,璇峰強鏃惰仈绯绘垜浠鏈嶏紒璋㈣阿鎮ㄣ��", "#00000")
//					.build();
//					System.out.println(tempjson);
//			boolean res=WxaTemplateUtil.sendTemplateMsg(tempjson);
//			System.out.println("妯℃澘娑堟伅鍙戦�佺粨鏋滐細"+res);
        }
        if (flag == 1) {
            this.successJson(flag, "update success", response);
        } else {
            this.errorJson(flag, "update fail", response);
        }
    }

    /**
     * 修改订单状态
     *
     * @param response
     * @param status
     * @param orderid
     */
    @RequestMapping(value = "updateOrder")
    public void updateOrder(HttpServletResponse response, Integer status, Integer orderid, String formid) {
        int flag = orderDAO.updateStatus(status, orderid);
        Order order = orderDAO.getById(orderid);
        Employee emp = employeeService.getByEmpId(order.getEmployeeId());
        Person person = null;
        if (emp != null) {
            person = employeeService.getById(emp.getPersonId());
        }
        Hunter hunter = hunterDAO.getById(order.getHunterId());
        OrderDesc orderdesc = orderDescDAO.getById(order.getOrdescId());
        System.out.println("退款=" + status + emp + hunter);
        if (status == 4 && emp != null && hunter != null) {
            wxPayRefundone(order.getOrdercode(), order.getTransactionId(), order.getPayMoney());
            // isbook:1已预定，0是未预定
            myCalendarDAO.updateIsBooking(order.getHunterId(), order.getOrderTime(), 0);
            // push candidate
            String tempjson = new WxaTemplate().setTouser(order.getOpenid())
                    .setTemplate_id("EVs9iI_hgd75QZzZnqakEZoAWJdfmrc0yn6VVFtaS_4").setForm_id(formid)
                    .setPage("pages/my-ordetail/my-ordetail?orderId=" + order.getId())
                    .add("keyword1", "YQS" + order.getOrdercode(), "#000000")
                    .add("keyword2", order.getOrderTime(), "#000000")
                    .add("keyword3", "￥" + orderdesc.getSpec() + "/" + orderdesc.getName() + "", "#F47e2d")
                    .add("keyword4", order.getPayMoney() * 0.01 + "元", "#000000")
                    .add("keyword5", "您已取消本次咨询的服务，且费用会在1-3个工作日内原路退回至您的账户中,谢谢您", "#00000").build();
            System.out.println(tempjson);
            boolean res = WxaTemplateUtil.sendTemplateMsg(tempjson);
            System.out.println("模板消息发送结果：" + res);
            // push hunter
            String tempjsonhunter = TemplateData.New().setTouser(hunter.getOpenid())
                    .setTemplate_id("4HValiBwcxDoz7PP0cUtNDXkWre-cGinZ4qJT2-RSBY")
                    .setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/toOrderDetail.do?orderId="
                            + order.getId())
                    .add("first", "您好，" + person.getName() + "已取消您的咨询服务，请悉知！", "#274084")
                    .add("keyword1", "YQS" + order.getOrdercode(), "#000000")
                    .add("keyword2", "￥" + orderdesc.getSpec() + "/" + orderdesc.getName() + "", "#F47e2d")
                    .add("keyword3", DateUtil.currentTime(), "#000000").add("remark", "非常感谢您，注意查收公众号最新信息。", "#274084")
                    .build();
            System.out.println(tempjsonhunter);
            ApiResult reshunter = TemplateMsgApi.send(tempjsonhunter);
            System.out.println("模板消息发送结果：" + reshunter);
        } else if (status == 3 && emp != null && hunter != null) {
            // push candidate
            String tempjson = new WxaTemplate().setTouser(order.getOpenid())
                    .setTemplate_id("M4YFvoQxRilM8kDEluWpRXBF05MJXmTyDAWOAIDsmWM").setForm_id(formid)
                    .setPage("pages/my-ordetail/my-ordetail?orderId=" + order.getId())
                    .add("keyword1", "YQS" + order.getOrdercode(), "#274084").add("keyword2", "已完成", "#000000")
                    .add("keyword3", order.getOrderMoney() + "元", "#F47e2d")
                    .add("keyword4", "￥" + orderdesc.getSpec() + "/" + orderdesc.getName(), "#000000")
                    .add("keyword5", "您好，您咨询的服务已完成，感谢信任，请前往小程序为本次的咨询师打分，谢谢您。", "#00000").build();
            System.out.println(tempjson);
            boolean res = WxaTemplateUtil.sendTemplateMsg(tempjson);
            System.out.println("模板消息推送结果：" + res);
            // push hunter
            String tempjsonhunter = TemplateData.New().setTouser(hunter.getOpenid())
                    .setTemplate_id("Fcl_B9YkEMq6hMzKAhMid8YH2QRJ9FT1Fmk74q8zD5I")
                    .setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/toOrderDetail.do?orderId="
                            + order.getId())
                    .add("first", "您好，您的咨询服务「订单号：YQS" + order.getOrdercode() + "」已完成，谢谢！", "#274084")
                    .add("keyword1", "￥" + orderdesc.getSpec() + "/" + orderdesc.getName() + "", "#000000")
                    .add("keyword2", hunter.getName(), "#F47e2d").add("keyword3", DateUtil.currentTime(), "#000000")
                    .add("remark", "非常感谢您，注意查收公众号最新信息。", "#274084").build();
            System.out.println(tempjsonhunter);
            ApiResult reshunter = TemplateMsgApi.send(tempjsonhunter);
            System.out.println("模板消息推送结果：" + reshunter);
        }

        if (flag == 1) {
            this.successJson(flag, "update success", response);
        } else {
            this.errorJson(flag, "update fail", response);
        }
    }

    /**
     * ----售后状态 status=-2 售后关闭 status=-1 卖家不同意售后协议，等待买家修改 status=0 售后协议等待卖家确认
     * status=1 售后成功，无需退款 status=2 有客服介入的售后 status=3 买家已发货，等待商家收货并同意退款 status=4
     * 商家同意退货协议，等待买家发货 status=5 商家同意退款，等待系统退款 status=6 售后成功，系统已退款
     */
    @RequestMapping(value = "createSafesales")
    public void createSafesales(HttpServletResponse response, String openid, String nickName, Integer status,
                                String orderId, String hunterId, String orderdescIds, String afterContent, Integer afterMoney) {
        // 提交修改order订单状态
        int flag = orderDAO.updateStatus(status, Integer.parseInt(orderId));
        if (flag == 1) {
            Safedsales safed = new Safedsales();
            safed.setOrderId(orderId);
            safed.setBuyerId(openid);
            safed.setBuyerName(nickName);
            safed.setOrderdescIds(orderdescIds);
            safed.setAfterReason(0);
            safed.setAfterRequest(0);
            safed.setAfterContent(afterContent);
            safed.setAfterMoney(afterMoney.doubleValue());
            safed.setAfterUpdateTime(DateUtil.currentTime());
            safed.setAfterCreateTime(DateUtil.currentTime());
            safed.setStatus(0);
            int result = safedsalesDAO.save(safed);
            log.info("申请维权result=" + result);
            this.successJson(result, "申请维权成功", response);
        } else {
            this.errorJson(flag, "申请维权失败", response);
        }

    }

    /**
     * 我的维权
     */
    @RequestMapping(value = "mysafed")
    public void mySafed(HttpServletResponse response, String openid) {
        List<Safedsales> list = safedsalesDAO.getBuyerSafedId(openid);
        for (Safedsales safed : list) {
            Hunter hunter = hunterDAO.getById(Integer.parseInt(safed.getHunterId()));
            if (hunter != null) {
                if (hunter.getDomainName1() != null) {
                    safed.setDomainName1(hunter.getDomainName1());
                } else {
                    Domain domain = domainDAO.getById(hunter.getMajordomain1());
                    safed.setDomainName1(domain.getName());
                }
                if (hunter.getDomainName2() != null) {
                    safed.setDomainName2(hunter.getDomainName2());
                } else {
                    Domain domain = domainDAO.getById(hunter.getMajordomain2());
                    safed.setDomainName2(domain.getName());
                }
                if (hunter.getDomainName3() != null) {
                    safed.setDomainName3(hunter.getDomainName3());
                } else {
                    Domain domain = domainDAO.getById(hunter.getMajordomain3());
                    safed.setDomainName3(domain.getName());
                }
                if (hunter.getCityName() != null) {
                    safed.setCityName(hunter.getCityName());
                } else {
                    City city = cityDAO.getById(hunter.getCityId());
                    safed.setCityName(city.getName());
                }
                safed.setWorkage(hunter.getWorkage());
            }
            if (safed.getStatus() == -2) {
                safed.setStatusName("维权关闭");
            } else if (safed.getStatus() == -1) {
                safed.setStatusName("咨询师不同意退款，等待用户修改");
            } else if (safed.getStatus() == 0) {
                safed.setStatusName("维权协议等待用户确认");
            } else if (safed.getStatus() == 1) {
                safed.setStatusName("维权成功，无需退款");
            } else if (safed.getStatus() == 2) {
                safed.setStatusName("有客服介入协调");
            } else if (safed.getStatus() == 3) {
                safed.setStatusName("咨询师同意退款，等待系统退款");
            } else if (safed.getStatus() == 4) {
                safed.setStatusName("维权成功，系统已退款");
            }
        }
        this.successJson(list, "我的维权", response);
    }

    @RequestMapping(value = "getSafedById")
    public void getSafedById(HttpServletResponse response, Integer safeId) {
        Safedsales safed = safedsalesDAO.getById(safeId);
        if (safed != null) {
            Hunter hunter = hunterDAO.getById(Integer.parseInt(safed.getHunterId()));
            if (hunter != null) {
                safed.setHunterName(hunter.getName());
                if (hunter.getDomainName1() != null) {
                    safed.setDomainName1(hunter.getDomainName1());
                } else {
                    Domain domain = domainDAO.getById(hunter.getMajordomain1());
                    safed.setDomainName1(domain.getName());
                }
                if (hunter.getDomainName2() != null) {
                    safed.setDomainName2(hunter.getDomainName2());
                } else {
                    Domain domain = domainDAO.getById(hunter.getMajordomain2());
                    safed.setDomainName2(domain.getName());
                }
                if (hunter.getDomainName3() != null) {
                    safed.setDomainName3(hunter.getDomainName3());
                } else {
                    Domain domain = domainDAO.getById(hunter.getMajordomain3());
                    safed.setDomainName3(domain.getName());
                }
                if (hunter.getCityName() != null) {
                    safed.setCityName(hunter.getCityName());
                } else {
                    City city = cityDAO.getById(hunter.getCityId());
                    safed.setCityName(city.getName());
                }
                safed.setWorkage(hunter.getWorkage());
            }
            if (safed.getStatus() == -2) {
                safed.setStatusName("维权关闭");
            } else if (safed.getStatus() == -1) {
                safed.setStatusName("咨询师不同意退款，等待用户修改");
            } else if (safed.getStatus() == 0) {
                safed.setStatusName("维权协议等待用户确认");
            } else if (safed.getStatus() == 1) {
                safed.setStatusName("维权成功，无需退款");
            } else if (safed.getStatus() == 2) {
                safed.setStatusName("有客服介入协调");
            } else if (safed.getStatus() == 3) {
                safed.setStatusName("咨询师同意退款，等待系统退款");
            } else if (safed.getStatus() == 4) {
                safed.setStatusName("维权成功，系统已退款");
            }
        }
        this.successJson(safed, "我的维权", response);
    }

    /**
     * 我的交易明细
     *
     * @param response
     * @param openid   display field :itemname,status,money,ordercode,updateTime
     */
    @RequestMapping(value = "myPayDetail")
    public void myPayDetail(HttpServletResponse response, String openid) {
        List<Order> orders = orderDAO.getOrderByOpenId(openid);
        for (Order order : orders) {
            int itemid = order.getOrdescId();
            OrderDesc orderDesc = orderDescDAO.getById(itemid);
            if (orderDesc != null) {
                order.setOrderdesc(orderDesc.getName());
                order.setOrdercode("YQS" + order.getOrdercode());
            }
        }
        this.successJson(orders, "我的交易明细", response);
    }

    /**
     * 是否订购薪酬分析总体建议
     *
     * @param response
     * @param openid
     */
    @RequestMapping(value = "isPaySalaryItem")
    public void isPaySalaryItem(HttpServletResponse response, String openid) {
        Long size = orderDAO.isPaySalaryItem(openid);
        this.successJson(size, "是否订购薪酬分析总体建议", response);
    }

    /**
     * 调用统一下单接口
     *
     * @param openId
     */
    private String unifiedOrder(String openId, String clientIP, Double totalfee, String randomNonceStr,
                                String randomOrderId, Integer ordescId) {

        try {

            String url = Const.URL_UNIFIED_ORDER;

            PayInfo payInfo = createPayInfo(openId, clientIP, totalfee, randomNonceStr, randomOrderId, ordescId);
            String md5 = getSign(payInfo);
            payInfo.setSign(md5);

            log.info("md5 value: " + md5);

            String xml = PayCommUtil.payInfoToXML(payInfo);
            xml = xml.replace("__", "_").replace("<![CDATA[1]]>", "1");
            // xml = xml.replace("__", "_").replace("<![CDATA[", "").replace("]]>", "");
            System.out.println(xml);

            StringBuffer buffer = UrlUtil.httpsRequest(url, "POST", xml);
            System.out.println("unifiedOrder request return body: \n" + buffer.toString());
            Map<String, String> result = PayCommUtil.parseXml(buffer.toString());

            String return_code = result.get("return_code");
            if (StringUtils.isNotBlank(return_code) && return_code.equals("SUCCESS")) {

                String return_msg = result.get("return_msg");
                if (StringUtils.isNotBlank(return_msg) && !return_msg.equals("OK")) {
                    log.error("统一下单错误！");
                    return "";
                }

                String prepay_Id = result.get("prepay_id");
                return prepay_Id;

            } else {
                return "";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    private PayInfo createPayInfo(String openId, String clientIP, Double totalfee, String randomNonceStr,
                                  String randomOrderId, Integer ordescId) {

        Date date = new Date();
        String timeStart = DateUtil.getFormatTime(date, Const.TIME_FORMAT);
        String timeExpire = DateUtil.getFormatTime(DateUtil.addDay(date, Const.TIME_EXPIRE), Const.TIME_FORMAT);
        OrderDesc orderdesc = orderDescDAO.getById(ordescId);
        PayInfo payInfo = new PayInfo();
        payInfo.setAppid(Const.APP_ID);
        System.out.println(Const.APP_ID);
        payInfo.setMch_id(Const.MCH_ID);
        System.out.println(Const.MCH_ID);
        payInfo.setDevice_info("WEB");
        payInfo.setNonce_str(randomNonceStr);
        payInfo.setSign_type("MD5"); // 默认即为MD5
        payInfo.setBody("￥" + orderdesc.getTag() + "/" + orderdesc.getName());
        payInfo.setAttach(ordescId.toString());
        payInfo.setOut_trade_no(randomOrderId);
        System.out.println(Math.round(totalfee));// 四舍五入取整，因为微信以分结算，精准到分没问题
        int money = (int) Math.round(totalfee);
        payInfo.setTotal_fee(money);
        payInfo.setSpbill_create_ip(clientIP);
        payInfo.setTime_start(timeStart);
        payInfo.setTime_expire(timeExpire);
        payInfo.setNotify_url(Const.URL_NOTIFY);
        payInfo.setTrade_type("JSAPI");
        payInfo.setLimit_pay("no_credit");
        payInfo.setOpenid(openId);

        return payInfo;
    }

    private String getSign(PayInfo payInfo) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append("appid=" + payInfo.getAppid()).append("&attach=" + payInfo.getAttach())
                .append("&body=" + payInfo.getBody()).append("&device_info=" + payInfo.getDevice_info())
                .append("&limit_pay=" + payInfo.getLimit_pay()).append("&mch_id=" + payInfo.getMch_id())
                .append("&nonce_str=" + payInfo.getNonce_str()).append("&notify_url=" + payInfo.getNotify_url())
                .append("&openid=" + payInfo.getOpenid()).append("&out_trade_no=" + payInfo.getOut_trade_no())
                .append("&sign_type=" + payInfo.getSign_type())
                .append("&spbill_create_ip=" + payInfo.getSpbill_create_ip())
                .append("&time_expire=" + payInfo.getTime_expire()).append("&time_start=" + payInfo.getTime_start())
                .append("&total_fee=" + payInfo.getTotal_fee()).append("&trade_type=" + payInfo.getTrade_type())
                .append("&key=" + Const.APP_KEY);

        System.out.println("排序后的拼接参数：" + sb.toString());

        return PayCommUtil.getMD5(sb.toString().trim()).toUpperCase();
    }

}
